﻿using System;
using System.Collections.Generic;
#if DEBUG
using System.Diagnostics;
#endif // #if DEBUG
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using FRL.DebtChased.Repository;
using FRL.DebtChased.Repository.ViewModels;
using FRL.DebtChased.Website;

namespace WebApplication.Finance
{

	/// <summary>
	/// Declaration of LetterTypeList
	/// </summary>
	public partial class LetterTypeList : System.Web.UI.Page
	{

		/////////////////////////////////////////////////////////////
		// Constants

		private const string ContextModelTag = "ContextModel";
		private const string ContextSelectedIdTag = "ContextSelectedId";

		/////////////////////////////////////////////////////////////
		// Attributes

		private LetterTypesModel ContextModel
		{
			get
			{
				return ViewState[ContextModelTag] as LetterTypesModel;
			}
			set
			{
				ViewState[ContextModelTag] = value;
			}
		}

		private int? ContextSelectedId
		{
			get 
			{ 
				return ViewState[ContextSelectedIdTag] as int?;
			}
			set 
			{ 
				ViewState[ContextSelectedIdTag] = value;
			}
		}

		/////////////////////////////////////////////////////////////
		// Event handlers

		protected override void OnPreRender(EventArgs e)
		{

			// Call base-class function
			base.OnPreRender(e);

			// Bind the model
			LetterTypesModel model = ContextModel;
#if DEBUG
			Debug.Assert(model != null);
#endif // #if DEBUG
			gridLetterType.DataSource = model.Elements;
			gridLetterType.DataBind();

			// Show/hide panels
			pnlEditing.Visible = (ContextSelectedId != null);

			// Set the panel colours
			MyApplication myApp = MyApplication.BindMyApplication();
			gridLetterType.RowStyle.BorderColor = myApp.SecondaryWebColor;

			// Enable/disable controls
			chkNewDays.Enabled = chkSpecificTime.Checked;
			cboNewHour.Enabled = chkSpecificTime.Checked;

		}

		protected void Page_Load(object sender, EventArgs e)
		{

			// If this is a postback...
			if (this.IsPostBack)
			{

				// Get the model
				LetterTypesModel model = ContextModel;
#if DEBUG
				Debug.Assert(model != null);
#endif // #if DEBUG

			}
			else
			{

				// Declare an entities object
				using (DebtChasedEntities ent = new DebtChasedEntities())
				{

					// Create the context model
					ContextModel = new LetterTypesModel(ent);

				}

				// Load the hours map
				Dictionary<int,string> hoursMap = ExtensionsForWebsites.LoadTimeMinutes();
				cboNewHour.BindToDictionary(hoursMap);

				// Load the days
				Dictionary<int,string> daysMap = LetterType.GetDaysDictionary();
				chkNewDays.BindToDictionary(daysMap);
				
				// Set the panel colours
				MyApplication myApp = MyApplication.BindMyApplication();
				pnlList.BackColor = myApp.PrimaryWebColor;
				pnlEditing.BackColor = myApp.PrimaryWebColor;
				pnlButtons.BackColor = myApp.PrimaryWebColor;
				gridLetterType.RowStyle.BorderColor = myApp.SecondaryWebColor;

			}

		}

		protected void gridLetterType_RowDataBound(object sender, GridViewRowEventArgs e)
		{

			// If this is a data-row...
			if (e.Row.RowType == DataControlRowType.DataRow)
			{

				// Get the model
				LetterTypesModel model = ContextModel;
#if DEBUG
				Debug.Assert(model != null);
#endif // #if DEBUG

				// Get the model element
				LetterTypesModel.Element el = e.Row.DataItem as LetterTypesModel.Element;

				// Setup the select button
				bool bIsAdmin = MySession.BindMySession().ContainsRole(Definitions.eRoles.FIN_SYSADMIN);
				if ( (el.UsageCount > 0) && (!bIsAdmin) )
				{
					DataControlFieldCell cell = e.Row.Cells[5] as DataControlFieldCell;
					cell.Enabled = false;
				}

				// Setup the delete button
				if (el.UsageCount > 0)
				{
					DataControlFieldCell cell = e.Row.Cells[6] as DataControlFieldCell;
					cell.Enabled = false;
				}

			}

		}

		protected void gridLetterType_RowCommand(object sender, GridViewCommandEventArgs e)
		{

			// Check the grid view object
			GridView gridView = sender as GridView;
#if DEBUG
			System.Diagnostics.Trace.Assert(gridView == gridLetterType);
#endif // #if DEBUG

			// Get row index
			int iRow = int.Parse(e.CommandArgument.ToString());

			// Convert argument to id
			int iLetterTypeId = int.Parse(gridLetterType.DataKeys[iRow].Value.ToString());
#if DEBUG
			Debug.Assert(iLetterTypeId != 0);
#endif // #if DEBUG

			// Get the model
			LetterTypesModel model = ContextModel;
#if DEBUG
			Debug.Assert(model != null);
#endif // #if DEBUG

			// Find the element in the model
			LetterTypesModel.Element el = model.FindByLetterTypeId(iLetterTypeId);

			// Compare commands
			if (e.CommandName == "DeleteLetterType")
			{

				// Delete the row from the model and re-bind
				model.Elements.Remove(el);

			}
			else if (e.CommandName == "Select")
			{

				// Set the context
				ContextSelectedId = iLetterTypeId;

				// Update controls
				txtNewName.Text = el.Name;
				cboNewHour.SelectedValue = el.TimeMinutes.ToString();
				if ((el.Days & LetterType.eDays.Immediate) != LetterType.eDays.Immediate)
				{
					for (int i1 = 0; i1 < chkNewDays.Items.Count; i1++)
					{
						ListItem li = chkNewDays.Items[i1];
						int iValue = int.Parse(li.Value);
						li.Selected = (((int)el.Days & iValue) == iValue);
					}
					chkSpecificTime.Checked = true;
				}
				else
					chkSpecificTime.Checked = false; 				

			}

		}

		protected void butRevert_Click(object sender, EventArgs e)
		{

			// Clear the context
			ContextSelectedId = null;

			// Clear selection
			gridLetterType.SelectedIndex = -1;

			// Reload the model
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Create the context model
				ContextModel = new LetterTypesModel(ent);

			}

		}

		protected void butOK_Click(object sender, EventArgs e)
		{

			// Get the user id
			int iUserId = MySession.BindMySession().UserID;
#if DEBUG
			if(iUserId==0)
				iUserId = 1;
#endif // #if DEBUG

			// Get the model
			LetterTypesModel model = ContextModel;
#if DEBUG
			Debug.Assert(model != null);
#endif // #if DEBUG

			// Declare an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Save the content
				string strError = model.Set(ent, iUserId);
				if (strError == null)
					Response.Redirect(this.AppRelativeVirtualPath);
				else
					(Page.Master as FinanceMaster).ErrorMessage = strError;

			}

		}

		protected void butAddNew_Click(object sender, EventArgs e)
		{

			// Set the context
			ContextSelectedId = 0;

			// Clear selection
			gridLetterType.SelectedIndex = -1;

			// Set the controls
			txtNewName.Text = "";

		}

		protected void butNewOK_Click(object sender, EventArgs e)
		{

			// Get the model
			LetterTypesModel model = ContextModel;
#if DEBUG
			Debug.Assert(model != null);
#endif // #if DEBUG

			// Get the control values
			string strName = txtNewName.Text;
			int iTimeMinutes = int.Parse(cboNewHour.SelectedValue);
			int iDays = 0;
			if (chkSpecificTime.Checked)
			{
				for (int i1 = 0; i1 < chkNewDays.Items.Count; i1++)
				{
					ListItem li = chkNewDays.Items[i1];
					int iValue = int.Parse(li.Value);
					if (li.Selected)
						iDays |= iValue;
				}
			}
			else
				iDays = (int)LetterType.eDays.Immediate;

			// If this is a new element...
			LetterTypesModel.Element el;
			if (ContextSelectedId == 0)
			{

				// Create a new element
				el = new LetterTypesModel.Element(model.GetNextNewId());				

			}
			else
			{

				// Update the model element
				el = model.FindByLetterTypeId(ContextSelectedId.Value);

			}

			// Check the controls
			string strError = null;
			if (strName.Length == 0)
				strError = "Enter a name.";
			else if(model.FindByName(strName,el)!=null)
				strError = "This name is already in use.";
			else if(iDays==0)
				strError = "Select at least one printing day.";
			if (strError != null)
			{
				(this.Master as FinanceMaster).ErrorMessage = strError;
				return;
			}

			// Update from controls
			el.Name = strName;
			el.TimeMinutes = iTimeMinutes;
			el.Days = (LetterType.eDays)iDays;

			// If new, add to element
			if (ContextSelectedId == 0)
				model.Elements.Add(el);

			// Clear selection
			gridLetterType.SelectedIndex = -1;

			// Set the context
			ContextSelectedId = null;

		}

		protected void butNewCancel_Click(object sender, EventArgs e)
		{

			// Clear selection
			gridLetterType.SelectedIndex = -1;

			// Set the context
			ContextSelectedId = null;

		}

	}

}
